package com.teamsun.util;

import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class CacheUtil {

    public static Map<String, List<Map<String, Object>>> cacheMap = new HashMap<String, List<Map<String, Object>>>();

    /**
     * 从缓存获取数据
     * @param key  缓存key
     * @param start 起始数据
     * @param end  结束数据
     * @return
     */
    public static List<Map<String, Object>> getCacheList(String key, int start, int end) {
        List<Map<String, Object>> pageList = null;
        if (cacheMap.containsKey(key)) {
            pageList = cacheMap.get(key);
            if (!CollectionUtils.isEmpty(pageList) && pageList.size() > start && end > start) {
                if (pageList.size() >= end) {
                    return pageList.subList(start, end);
                } else if (pageList.size() < end) {
                    return pageList.subList(start, pageList.size());
                }
            }
        }
        return null;
    }

    /**
     * 清除缓存
     * @param key
     */
    public static void deleteListByKey(String key) {
        if (cacheMap.containsKey(key)) {
            cacheMap.remove(key);
        }

        Iterator<String> iterator = cacheMap.keySet().iterator();
        while (iterator.hasNext()) {
            String entryKey = iterator.next();
            String entryKeyTime = entryKey.substring(entryKey.lastIndexOf("-") + 1);
            try {
                //清除超过15分钟的缓存数据，删除失败的补偿机制
                if (System.currentTimeMillis() - (Long.parseLong(entryKeyTime)) >= 15 * 60 * 1000) {
                    iterator.remove();
                    cacheMap.remove(entryKey);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
